import {ParamsType} from "@ant-design/pro-components";
import {ResponseStructure} from "@/requestErrorConfig";
import {request} from "umi";

/**
 * API 请求接口，用于在React函数当中快速发送请求
 *
 * @author 橘柚
 * @Date 2025/3/18 17:20
 * @Description
 */
interface IApiService {
  get: (endpoint: string, params?: ParamsType, options?: DynamicObject) => Promise<ResponseStructure>;
  pageData: (params?: ParamsType, options?: DynamicObject) => Promise<ResponseStructure>;
  listData: (params?: ParamsType, options?: DynamicObject) => Promise<ResponseStructure>;
  addData: <T>(data: T, options?: DynamicObject) => Promise<ResponseStructure>;
  updateById: <T>(data: T, options?: DynamicObject) => Promise<ResponseStructure>;
  deleteById: (id: string | number, options?: DynamicObject) => Promise<ResponseStructure>;
}

export const useApiService = (baseUrl: string): IApiService => {

  const get = async (endpoint: string, params?: ParamsType, options?: DynamicObject) => {
    return request<ResponseStructure>(`/api${baseUrl}${endpoint}`, {
      method: "GET",
      params: {...params},
      ...(options || {}),
    });
  };

  const pageData = async (params?: ParamsType, options?: DynamicObject) => {
    return request<ResponseStructure>(`/api/${baseUrl}/page`, {
      method: "GET",
      params: {...params},
      ...(options || {}),
    });
  };

  const listData = async (params?: ParamsType, options?: DynamicObject) => {
    return request<ResponseStructure>(`/api/${baseUrl}/list`, {
      method: "GET",
      params: {...params},
      ...(options || {}),
    });
  };

  const addData = async <T>(data: T, options?: DynamicObject) => {
    return request<ResponseStructure>(`/api/${baseUrl}`, {
      method: "POST",
      data,
      ...(options || {}),
    });
  };

  const updateById = async <T>(data: T, options?: DynamicObject) => {
    return request<ResponseStructure>(`/api/${baseUrl}/updateById`, {
      method: "PUT",
      data,
      ...(options || {}),
    });
  };

  const deleteById = async (id: string | number, options?: DynamicObject) => {
    return request<ResponseStructure>(`/api/${baseUrl}/${id}`, {
      method: "DELETE",
      ...(options || {}),
    });
  };

  return {get, pageData, listData, addData, updateById, deleteById};
};
